/*
 * Task.hpp
 *
 *  Created on: 03.12.2012
 *      Author: zheka
 */

#ifndef TASK_HPP
#define TASK_HPP

#include "Context.hpp"
#include <string>
#include "util/Log.hpp"
#include "util/StringUtils.hpp"
#include <vector>
#include <algorithm>
#include <sys/socket.h>
#include "util/ProxyException.hpp"
class Task {
private:
	int fileDescriptor;

	static std::vector<Task*> instances;
protected:
	Task();
explicit	Task(int fileDescriptor) :
		fileDescriptor(fileDescriptor) {
	instances.push_back(this);

	Log::v(StringUtils::toString((int)this)+" !!!! new Task() ["+StringUtils::toString(getFileDiscriptor())+"] count="+StringUtils::toString(instances.size()));
	}
	  std::string   read(const int bufferSize );
	  std::string   write(const std::string & source);
	  size_t   write(const std::string & source, size_t offset);
public:
	  virtual ~Task() {
instances.erase(std::find(instances.begin(), instances.end(), this));
Log::v("==== DELETE Task() ["+StringUtils::toString(getFileDiscriptor())+"] count="+StringUtils::toString(instances.size())+" ====");
Log::v("==== BEGIN OF TASK LIST ====");
for(size_t i=0; i<instances.size(); i++) {
	Log::v("Available "+StringUtils::toString((int)instances[i])+" "+instances[i]->toString());
}
Log::v("==== END OF TASK LIST ====");

	  }
	static const int BUFFER_SIZE;
	int getFileDiscriptor() ;
	void setFileDiscriptor(int fileDescriptor) ;
	virtual void onInit(Context & context) {};
	virtual void onDestroy(Context & context);
	virtual void onRead(Context & context) {};
	virtual void onWrite(Context & context) {};
	virtual std::string toString() ;
	void checkSocket() {
		int optval = 0;
				int optlen = sizeof(optval);
				if (getsockopt(fileDescriptor, SOL_SOCKET, SO_ERROR, &optval,
						&optlen) < 0) {

					throw ProxyException("[Task] Cant getopt!");
				}
				if(optval != 0) {
					throw ProxyException("[Task] Sock error!");
				}
	}
};
#endif /* TASK_HPP */
